package tidb

import (
	"douhu_backend/internal/config"
	"fmt"
	"log"
	"sync"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/plugin/dbresolver"
)

var (
	dbOnce sync.Once
	DB     *gorm.DB
	dbName = "douhu"
	useSSL = "false"
)

type Client struct {
}

// TODO: 确认是要传入LB 地址还是集群每个节点的地址
// TODO: 配置连接池大小
func NewClient(addrs []string, user, password string) (*Client, error) {

	dbName := "mos"
	useSSL := "false"
	dsnWrite := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&tls=%s&parseTime=True&loc=Local",
		user, password, addrs[0], dbName, useSSL)

	client := &Client{}
	var err error

	dbOnce.Do(func() {

		DB, err = gorm.Open(mysql.Open(dsnWrite), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Error),
		})
		if err != nil {
			log.Fatalln("gorm.Open: ", err.Error())
		}

		replicas := make([]gorm.Dialector, 0)
		for _, addr := range addrs {
			dsnRead := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&tls=%s&parseTime=True&loc=Local",
				user, password, addr, dbName, useSSL)
			replicas = append(replicas, mysql.Open(dsnRead))
		}
		// 配置多个读节点
		err = DB.Use(dbresolver.Register(dbresolver.Config{
			Replicas: replicas,
			Policy:   dbresolver.RandomPolicy{}, // 随机选择读节点
		}))

	})

	return client, err

}

// NewDB creates a new database connection using config file settings
func NewDB() (*gorm.DB, error) {
	// Use global config instance
	if config.Conf == nil || config.Conf.DB == nil {
		return nil, fmt.Errorf("database configuration not found")
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s",
		config.Conf.DB.Username,  // username from config
		config.Conf.DB.Password,  // password from config
		config.Conf.DB.Address,   // address from config
		config.Conf.DB.DBName,    // database name from config
		config.Conf.DB.Options)   // options from config

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return nil, fmt.Errorf("failed to connect to database: %v", err)
	}

	return db, nil
}
